package com.adcc.ags.gms.user.service;

import com.adcc.ags.gms.core.entity.GWLogLevel;
import com.adcc.ags.gms.core.util.LogFactory;
import com.adcc.ags.gms.user.entity.GWUser;
import com.adcc.ags.gms.user.entity.Route;
import com.adcc.ags.gms.user.mapper.GWUserMapper;
import com.adcc.ags.gms.user.mapper.RouteMapper;
import com.adcc.ags.gms.user.vo.GWUserNodeVO;
import com.adcc.ags.gms.user.vo.GWUserTreeVO;
import com.adcc.ags.gms.user.vo.GWUserVO;
import com.adcc.ags.gms.user.vo.RouteVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 路由服务层
 */
@Service("RouteService")
public class RouteServiceImpl implements RouteService {

    @Autowired
    private GWUserMapper gwUserMapper;

    @Autowired
    private RouteMapper routeMapper;

    @Autowired
    private LogFactory log;

    @Override
    public Optional<GWUserTreeVO> initGWUserTree() {
        try{
            GWUserTreeVO result = new GWUserTreeVO();
            List<GWUser> list = gwUserMapper.findAllGWUser();
            if(list != null && list.size() > 0){
                for(GWUser user : list){
                    GWUserNodeVO vo = new GWUserNodeVO(user);
                    result.getNodeList().add(vo);
                }
                result.getNodeList().get(0).setSelected(true);
            }
            return Optional.of(result);
        }catch (Exception ex){
            log.error(RouteService.class, "Route", GWLogLevel.ALARM, "initGWUserTree() error", ex);
            return Optional.absent();
        }
    }

    @Override
    public Optional<List<GWUserVO>> initGWUserList(long userId) {
        try{
            List<GWUserVO> result = Lists.newArrayListWithExpectedSize(1000);
            List<GWUser> list = gwUserMapper.findAllGWUser();
            if(list != null && list.size() > 0){
                for(GWUser user : list){
                    if(user.getId() == userId){
                        continue;
                    }
                    GWUserVO vo = new GWUserVO(user);
                    result.add(vo);
                }
            }
            return Optional.of(result);
        }catch (Exception ex){
            log.error(RouteService.class, "Route", GWLogLevel.ALARM, "initGWUserList() error", ex);
            return Optional.absent();
        }
    }

    @Override
    public Optional<PageInfo<Route>> findRouteByUserId(long userId, int currentPage, int pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        try {
            List<Route> routeList = routeMapper.findByUser(userId);
            PageInfo<Route> pageInfo = new PageInfo<>(routeList);
            return Optional.of(pageInfo);
        } catch (Exception e) {
            log.error(RouteService.class, "Route", GWLogLevel.ALARM, "findRouteByUserId() error", e);
            return Optional.absent();
        }
    }

    @Override
    public Optional<PageInfo<Route>> findRouteByNameAndType(String name,int type,long userId,int currentPage, int pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        try {
            Route route = new Route();
            String strName = Strings.nullToEmpty(name);
            if(!Strings.isNullOrEmpty(strName)){
                strName = "%" + strName + "%";
                route.setName(strName);
            }
            route.setType(type);
            route.setGwUserId(userId);
            List<Route> routeList  = routeMapper.findRouteByNameAndType(route);
            PageInfo<Route> pageInfo = new PageInfo<>(routeList);
            return Optional.of(pageInfo);
        } catch (Exception e) {
            log.error(RouteService.class, "Route", GWLogLevel.ALARM, "findAllRouteConfigsByCondition() error", e);
        }
        return Optional.absent();
    }

    @Override
    public Optional<Boolean> createRoute(RouteVO vo) {
        try {
            Route route = vo.toEntity();
            routeMapper.createRoute(route);

            // 记录日志
            GWUser gwUser = gwUserMapper.findGWUserById(route.getGwUserId());
            log.info(RouteService.class, gwUser.getUserName(), "路由："+vo.getName()+"新增");
            return Optional.of(true);
        } catch (Exception ex) {
            // 记录日志
            log.error(RouteService.class, "Route", GWLogLevel.ALARM, "路由：" + vo.getName() + "新增，失败", ex);
            return Optional.absent();
        }
    }

    @Override
    public Optional<Boolean> updateRoute(RouteVO vo) {
        try {
            Route route = vo.toEntity();
            routeMapper.updateRoute(route);

            // 记录日志
            GWUser gwUser = gwUserMapper.findGWUserById(route.getGwUserId());
            log.info(RouteService.class, gwUser.getUserName(), "路由："+vo.getName()+"修改");
            return Optional.of(true);
        } catch (Exception ex) {
            // 记录日志
            log.error(RouteService.class, "Route", GWLogLevel.ALARM, "路由：" + vo.getName() + "修改，失败", ex);
            return Optional.absent();
        }
    }

    @Override
    public Optional<Boolean> deleteSelectedRoute(String[] ids) {
        List<String> strs = new ArrayList<String>();
        try {
            List<Route> routes = routeMapper.findRoutesByRouteIds(ids);
            for(Route route : routes){
                strs.add(route.getName());
            }
            routeMapper.deleteSelectedRoute(ids);

            // 记录日志
            GWUser gwUser = gwUserMapper.findGWUserById(routes.get(0).getGwUserId());
            log.info(RouteService.class, gwUser.getUserName(), "路由：" + StringUtils.join(strs, ",") + "删除");
            return Optional.of(true);
        } catch (Exception ex) {
            // 记录日志
            log.error(RouteService.class, "Route", GWLogLevel.ALARM, "路由：" + StringUtils.join(strs, ",") + "删除，失败", ex);
            return Optional.absent();
        }
    }

    @Override
    public Optional<Boolean> isExistRouteName(String name) {
        try {
            int intCount = routeMapper.isExistRouterName(name);
            if (intCount > 0) {
                return Optional.of(true);
            } else {
                return Optional.of(false);
            }
        } catch (Exception ex) {
            log.error(RouteService.class, "Route", GWLogLevel.ALARM, "isExistGWUserName() error", ex);
            return Optional.absent();
        }
    }

    @Override
    public List<String> findUserNameById(String[] id) {
        try {
            List<String> result = null;
            result = routeMapper.findUserNameById(id);
            return result;
        } catch (Exception e) {
            log.error(RouteService.class, "Route", GWLogLevel.ALARM, "findUserNameById() error", e);
            return null;
        }
    }
}
